import io,sys,re

import rdflib
from rdflib import Graph
from rdflib import Namespace
from rdflib import Literal

prefix = Namespace('http://purl.org/twc/cos#')
skos = Namespace('http://www.w3.org/2004/02/skos/core#')
rdf = Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')

def makeURI(term):
    localPart = term.replace(' ','_')
    localPart = localPart.replace('&','and')
    localPart = re.sub('[\'\(\)\[\]\{\}:!@#$%^*()\\|<>?/-]"','',localPart)
    localPart = localPart.lower()
    return prefix[localPart]

inputfile = open(sys.argv[1], 'rb')

graph = Graph()

termStack = []
indentStack = []
for line in inputfile:
    m = re.match('^(\s*)(.+)',line)
    if m == None: continue
    indent = len(m.group(1))
    term = m.group(2).strip()
    uri = makeURI(term)
    graph.add((uri,skos['prefLabel'],Literal(term)))
    graph.add((uri,rdf['type'],skos['Concept']))

    broaderTerm = None
    while len(indentStack) > 0 and indent <= indentStack[-1]:
	indentStack.pop()
	termStack.pop()
    if len(indentStack) == 0:
	termStack.append(uri)
	indentStack.append(indent)
	continue
    if indent == indentStack[-1]:
	termStack[-1] = uri
	broaderTerm = termStack[-2]
    elif indent > indentStack[-1]:
	broaderTerm = termStack[-1]
	termStack.append(uri)
	indentStack.append(indent)
    graph.add((uri,skos['broader'],broaderTerm))
    graph.commit()

outputfile = open(sys.argv[2], 'w')
outputfile.write(graph.serialize())
